import json
import os
import sys

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from config import *
from aws_model.athena_submit import submit
from base_class.base_utils import spend_time
from base_class.inspect_logging import print_to_log


# 源表和目标表
# client = boto3.client('athena')

@spend_time("一个型号一天耗时： ")
def insert_washer_mapping(is_hour,mapping_json, materials, p_date):
    if is_hour:
        target_table = washer_target_table_hour
        source_table = washer_hbase_table_hour
    else:
        target_table = washer_target_table
        source_table = washer_hbase_table

    mappings = json.loads(mapping_json)
    source_columns = [f'"COALESCE(TRY(CAST ({k} AS {mappings[k]["data_type"]})),null)"' for k in mappings]
    target_columns = [f'"{v["value"]}"' for v in mappings.values()]
    # 重复的字段的数据来源"
    query = f"""INSERT INTO {target_table} (sn, timeStamp, {",".join(target_columns)})
    SELECT
                substr(rowkey, 27, 24) as sn ,
                date_format(from_unixtime(cast(substr(cast(9223372036854775807-cast(substr(rowkey, 8, 19) as bigint) as varchar),1,10) as bigint), 'Asia/Shanghai'), '%Y-%m-%d %H:%i:%s' ) as timeStamp,
                {",".join(source_columns)} FROM {source_table} WHERE """
    query = query.replace('"', "")
    query += f" p_date = '{p_date}'"
    query += f''' and material in ({"'" + "','".join(materials) + "'"}) '''
    result = submit(query)
    print_to_log(p_date, materials, result)
